<!--
 * @Description: 购房人年龄构成
 * @Author: py
 * @Date: 2024-11-04
-->
<script setup lang='ts'>
import type { EChartsOption } from 'echarts'

import { useBar } from '@fl/api/data-analysis'
import { Echart } from '@fl/origin-components/Echart'
import { set } from 'lodash-es'

import type { DateRange } from '../types'

const props = withDefaults(defineProps<{
    statisticsType: string
}>(), {
    statisticsType: '',
})
const { statisticsType } = toRefs(props)

const oDateRange = inject<Ref<DateRange>>('dateRange')
if (!oDateRange) {
    throw new Error('dateRange is not provided by an ancestor component.')
}

const womanSourceDatas = ref([])
const manSourceDatas = ref([])

function sumCalc(numArr: number[]) {
    return numArr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
}

const totalWoman = computed(() => sumCalc(womanSourceDatas.value))
const totalMan = computed(() => sumCalc(manSourceDatas.value))
const totalPeople = computed(() => totalWoman.value + totalMan.value)
const womanRates = computed(() => womanSourceDatas.value.map(val => totalPeople.value === 0 ? 0 : val / totalPeople.value))
const manRates = computed(() => manSourceDatas.value.map(val => totalPeople.value === 0 ? 0 : val / totalPeople.value))
const agePeopleRates = computed(() => womanRates.value.map((val, index) => val + manRates.value[index]))

const chartOptions = reactive({
    grid: {
        bottom: 0,
        containLabel: true,
        left: 0,
        right: 50,
        top: 25,
    },
    legend: {
        data: [
            {
                name: '女性',
            },
            {
                name: '男性',
            },
        ],
        itemGap: 20,
        itemHeight: 12,
        itemWidth: 12,
        left: 'center',
        padding: 0,
        textStyle: {
            color: '#86909c',
            fontSize: 12,
            lineHeight: 12,
        },
        top: 'top',
    },
    series: [
        {
            barWidth: 30,
            data: [],
            itemStyle: {
                color: '#F723C7',
            },
            name: '女性',
            stack: 'rate',
            type: 'bar',
        },
        {
            barWidth: 30,
            data: [],
            itemStyle: {
                color: '#5b8ff9',
            },
            name: '男性',
            stack: 'rate',
            type: 'bar',
        },
        {
            barGap: '-100%',
            barWidth: 30,
            data: [],
            itemStyle: {
                color: 'transparent',
            },
            label: {
                color: '#1d2129',
                formatter: (params: any) => {
                    // console.log(params)
                    const value = params.value ?? 0
                    return value === 0 ? '0' : `${(value * 100).toFixed(2)}%`
                },
                position: 'right',
                show: true,
            },
            name: '年龄段占比',
            type: 'bar',
        },
    ],
    tooltip: {
        axisPointer: {
            type: 'shadow',
        },
        formatter: (params) => {
            // console.log(params)
            const womanNum = params[0].value === 0 ? '0' : `${(params[0].value * 100).toFixed(2)}%`
            const manNum = params[1].value === 0 ? '0' : `${(params[1].value * 100).toFixed(2)}%`
            // const womanNum = womanSourceDatas.value[params[0].dataIndex]
            // const manNum = manSourceDatas.value[params[1].dataIndex]
            return `
              <div style="font-size: 14px;">
                <span style="margin-right: 3px;">${params[0].seriesName}</span>
                <span>${womanNum}</span>
              </div>
              <div style="font-size: 14px;">
                <span style="margin-right: 3px;">${params[1].seriesName}</span>
                <span>${manNum}</span>
              </div>
            `
        },
        trigger: 'axis',
    },
    xAxis: {
        axisLabel: {
            color: '#86909c',
            formatter: (val) => {
                return val === 0 ? '0' : `${Math.round(val * 100)}%`
            },
        },
        axisLine: {
            show: false,
        },
        type: 'value',
    },
    yAxis: {
        axisLabel: {
            color: '#86909c',
        },
        axisLine: {
            show: false,
        },
        axisTick: {
            alignWithLabel: true,
            show: false,
        },
        data: ['70后', '80后', '90后', '00后', '其他'],
        inverse: true,
        type: 'category',
    },
}) as EChartsOption

const oParams = computed(() => {
    return {
        endTime: oDateRange.value.endTime,
        startTime: oDateRange.value.startTime,
        type: statisticsType.value === 'couponUsers' ? 10 : 11, // 10 领券人 11 购房人
    }
})

const { data: chartsData, isLoading: chartsLoading } = useBar(oParams)

watchEffect(() => {
    if (chartsData.value) {
        const { legendData, seriesData } = chartsData.value
        womanSourceDatas.value = seriesData[1].data
        manSourceDatas.value = seriesData[0].data

        set(
            chartOptions,
            'yAxis.data',
            legendData,
        )
        set(
            chartOptions,
            'series[0].data',
            womanRates.value,
        )
        set(
            chartOptions,
            'series[1].data',
            manRates.value,
        )
        set(
            chartOptions,
            'series[2].data',
            agePeopleRates.value,
        )
    }
})
</script>

<template>
    <div class="pr-20">
        <h5 class="module-title">
            购房人年龄构成
        </h5>

        <div class="chart-container">
            <ElSkeleton :loading="chartsLoading"
                        animated
            >
                <Echart :options="chartOptions"
                        :height="300"
                />
            </ElSkeleton>
        </div>
    </div>
</template>

<style lang="less" scoped>
@import '../panel.less';

.chart-container {
    width: 100%;
}
</style>
